import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:ball_lion/base/base_controller.dart';
import 'package:ball_lion/module/record/channel_logic.dart';
import 'package:ball_lion/module/record/hot_channel_logic.dart';
import 'package:ball_lion/module/record/rank_logic.dart';
import 'package:ball_lion/server/api/record_api.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/module/record/channel_focus_page.dart';
import 'package:ball_lion/module/record/hot_channel_page.dart';
import 'package:ball_lion/module/record/rank_page.dart';
import 'package:ball_lion/entity/record/channel_entity.dart';
import 'package:ball_lion/module/record/channel_page.dart';

class RecordLogic extends BaseController with GetTickerProviderStateMixin {
  late final TabController headController;
  late TabController lqController;
  late TabController zqController;
  int _lqIndex = 1;
  int _zqIndex = 1;
  List<List<ChannelEntity>> _data = [];
  int _headIndex = 0;
  int count = 0;
  bool isLoading = true;
  List<List<String>> tabList = [
    ["关注", "热门", "FIFA俱乐部", "FIFA国家队"],
    ["关注", "热门", "FIBA国家队"]
  ];
  List<List<Widget>> channelPages = [
    [
      const ChannelFocusPage(sportsId: 1),
      const HotChannelPage(type: 0),
      RankPage(tag: "俱乐部"),
      RankPage(tag: "国家队")
    ],
    [
      const ChannelFocusPage(sportsId: 2),
      const HotChannelPage(type: 1),
      RankPage(tag: "篮球")
    ]
  ];
  late List<int> initialPlace =
      tabList.map((e) => e.indexOf("热门") + 1).toList();
  late List<int> lastPlace = List.generate(tabList.length,
      (index) => tabList[index].indexOf(index == 0 ? "FIFA俱乐部" : "FIBA国家队"));
  List<List<ChannelEntity>> old = [];

  List<List<ChannelEntity>>? get data => _data;
  int get headIndex => _headIndex;
  int get lqIndex => _lqIndex;
  int get zqIndex => _zqIndex;

  set zqIndex(int value) {
    _zqIndex = value;
    update();
  }

  set lqIndex(int value) {
    _lqIndex = value;
    update();
  }

  set headIndex(int value) {
    _headIndex = value;
    update();
  }

  @override
  void onInit() {
    super.onInit();
    headController = TabController(length: 2, vsync: this);
    headController.addListener(() {
      headIndex = headController.index;
    });
  }

  @override
  void onReady() {
    getData();
    super.onReady();
  }

  Future getData() async {
    for (var i = 0; i < 2; i++) {
      _data.add(await RecordApi.myChannels(i) ?? []);
      old.add(await RecordApi.myChannels(i) ?? []);
      try {
        tabList[i].insertAll(
            initialPlace[i], _data[i].map((e) => e.channelName ?? "").toList());
        channelPages[i].insertAll(
            initialPlace[i],
            List.generate(
                _data[i].length,
                (childIndex) => ChannelPage(
                    data: _data[i][childIndex],
                    type: i,
                    key: Key("${_data[i][childIndex].channelId}$i"))));
        lastPlace[i] = tabList[i].indexOf(i == 0 ? "FIFA俱乐部" : "FIBA国家队");
      } catch (e) {
        Logger().d(e);
      }
      if (i == 0) {
        zqController = TabController(
            length: tabList[i].length,
            vsync: this,
            initialIndex: tabList[i].indexOf("热门"));
        zqController.addListener(() {
          zqIndex = zqController.index;
        });
      } else {
        lqController = TabController(
            length: tabList[i].length,
            vsync: this,
            initialIndex: tabList[i].indexOf("热门"));
        lqController.addListener(() {
          lqIndex = lqController.index;
        });
      }
    }
    isLoading = false;
    update();
  }

  Future updateData(int index) async {
    _data[index].replaceAll(await RecordApi.myChannels(index) ?? []);
    bool cheekLength = false;
    bool checkTab = false;
    if (_data[index].length != old[index].length) {
      cheekLength = true;
    } else {
      for (var i = 0; i < _data[index].length; i++) {
        if (_data[index][i].channelId != old[index][i].channelId) {
          checkTab = true;
          break;
        }
      }
    }
    if (cheekLength || checkTab) {
      count += 1;
      tabList[index].removeRange(initialPlace[index], lastPlace[index]);
      channelPages[index].removeRange(initialPlace[index], lastPlace[index]);
      tabList[index].insertAll(initialPlace[index],
          _data[index].map((e) => e.channelName ?? "").toList());
      channelPages[index].insertAll(
          initialPlace[index],
          List.generate(
              _data[index].length,
              (childIndex) => ChannelPage(
                  data: _data[index][childIndex],
                  type: index,
                  key: Key("${_data[index][childIndex].channelId}$index"))));
      if (index == 0) {
        var oldIndex = zqController.index;
        if (tabList[index].length - 1 < oldIndex) {
          oldIndex = tabList[index].length - 1;
        }
        zqController.dispose();
        zqController = TabController(
            length: tabList[index].length, vsync: this, initialIndex: oldIndex);
        zqIndex = oldIndex;
        zqController.addListener(() => zqIndex = zqController.index);
      } else {
        var oldIndex = lqController.index;
        if (tabList[index].length - 1 < oldIndex) {
          oldIndex = tabList[index].length - 1;
        }
        lqController.dispose();
        lqController = TabController(
            length: tabList[index].length, vsync: this, initialIndex: oldIndex);
        zqIndex = oldIndex;
        lqController.addListener(() {
          lqIndex = lqController.index;
        });
      }
      lastPlace[index] =
          tabList[index].indexOf(index == 0 ? "FIFA俱乐部" : "FIBA国家队");
      old[index].replaceAll(_data[index]);
      update();
    }
  }

  void doRefresh() {
    if (headIndex == 0) {
      if (zqIndex == tabList[headIndex].indexOf("关注")) {
      } else if (zqIndex == tabList[headIndex].indexOf("热门")) {
        Get.find<HotChannelLogic>(tag: "0").doRefresh();
      } else if (zqIndex == tabList[headIndex].indexOf("俱乐部")) {
        Get.find<RankLogic>(tag: "俱乐部").doRefresh();
      } else if (zqIndex == tabList[headIndex].indexOf("国家队")) {
        Get.find<RankLogic>(tag: "国家队").doRefresh();
      } else {
        Get.find<ChannelLogic>(tag: "${_data[0][zqIndex - 4].channelId}0")
            .doRefresh();
      }
    } else {
      if (zqIndex == tabList[headIndex].indexOf("关注")) {
      } else if (lqIndex == tabList[headIndex].indexOf("热门")) {
        Get.find<HotChannelLogic>(tag: "1").doRefresh();
      } else if (lqIndex == tabList[headIndex].indexOf("篮球")) {
        Get.find<RankLogic>(tag: "篮球").doRefresh();
      } else {
        Get.find<ChannelLogic>(tag: "${_data[1][lqIndex - 3].channelId}1")
            .doRefresh();
      }
    }
  }

  @override
  void getRefresh() {
    updateData(0);
    updateData(1);
    super.getRefresh();
  }
}
